package com.maycurobj.controller.maycur;

import com.alibaba.fastjson.JSONObject;
import com.maycurobj.pojo.MayCurCallback;
import com.maycurobj.service.impl.MaycurTodoServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * 每刻 To_do callback
 */
@Controller
@RequestMapping("/maycur/callback")
@Slf4j
public class MaycurTodoCallBackController {

    @Autowired
    private MaycurTodoServiceImpl maycurTodoService;

    /**
     * 每刻回调 方法
     */
    @PostMapping("/getTodoBack")
    @ResponseBody
    public JSONObject maycurTodoShakeHands(@RequestBody JSONObject entity) {
        log.info("每刻 单据流程 回调接口报文----->{}", JSONObject.toJSONString(entity));
        //特殊的异常处理 可以用于 首次验证
        if(!entity.containsKey("calloutParams")){
            return res();
        }
        //对象转换
        MayCurCallback obj = entity.getJSONObject("calloutParams") != null ? entity.getJSONObject("calloutParams").toJavaObject(MayCurCallback.class) : null;
        String ret = "不需要执行";
        String eventScenario = obj.getEventScenario();
        if (!Objects.isNull(obj) && (eventScenario.equals("APPROVAL") || eventScenario.equals("FINANCE_AUDIT"))) {
            //执行 任务业务处理服务
            ret = maycurTodoService.proccessIamTodo(obj);
        }
        log.info("待办执行结果---->{}", ret);
        //所有回调全部返回正常
        return res();
    }


    private JSONObject res() {
        JSONObject ret = new JSONObject();
        ret.put("success", true);
        ret.put("errorMsg", "成功");
        return ret;
    }

    /**
     * 首次 每刻确认链接方法 (临时)
     *
     * @param entity
     * @return
     */
    @PostMapping("/getTodoBack/frist")
    @ResponseBody
    public JSONObject maycurTest(@RequestBody JSONObject entity) {
        log.info("测试maycurTest---->{}", JSONObject.toJSONString(entity));
        JSONObject ret = new JSONObject();
        ret.put("success", true);
        ret.put("errorMsg", "成功");
        return ret;
    }

}
